package com.atwisdom.star.core.dsl.functionClass.Impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.atwisdom.star.core.dao.pojo.functionClass.BatchNumber;
import com.atwisdom.star.core.dao.service.functionClass.impl.BatchNumberServiceImpl;
import com.atwisdom.star.core.dsl.functionClass.BatchNumberDslService;
import com.atwisdom.star.exception.pojo.BusinessException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @author fushb
* @description 针对表【batch_number】的数据库操作Service实现
* @createDate 2023-02-14 00:51:14
*/
@Service
public class BatchNumberDslServiceImpl implements BatchNumberDslService {
    @Autowired
    private BatchNumberServiceImpl batchNumberService;

    /**
     * 获取批次号当前值
     *
     * @param param 参数据
     * @return 返回值
     */
    @Override
    public String getCurrentVal(Map<String, String> param) {
        try {
            String name = param.get("name");
            QueryWrapper<BatchNumber> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", name);
            BatchNumber batchNumber = batchNumberService.getOne(queryWrapper);
            Integer currentValue = batchNumber.getCurrentValue();
            return name + "-" + currentValue;
        }catch (Exception ex){
            throw new BusinessException("999999","获取批次号数据异常",ex);
        }
    }

    /**
     * 获取批次号当前值
     *
     * @param code 参数据
     * @return 返回值
     */
    @Override
    public String getCurrentValByCode(String code) {
        try {
            QueryWrapper<BatchNumber> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", code);
            BatchNumber batchNumber = batchNumberService.getOne(queryWrapper);
            Integer currentValue = batchNumber.getCurrentValue();
            String name = batchNumber.getName();
            return name + "-" + currentValue;
        }catch (Exception ex){
            throw new BusinessException("999999","获取批次号数据异常",ex);
        }
    }
    /**
     *  处理自动生成的字段
     *  yyyyMMddHHmmssSSS
     * @param value
     * @return
     */
    @Transactional
    @Override
    public String fetchAutoGen(String value) {
        value = value.replace("autogen.", "");
        // codeRule: 'sale-YYYY':  年可能是 YYYY 或者 YY,  autogen.A32-fetchBatchNumber(A32)
        if (value.contains("simpleUUID")) {
            value = value.replace("simpleUUID", IdUtil.simpleUUID());
        } else if (value.contains("yyyyMMddHHmmss")) {
            value = fetchBatchNumber(value, "yyyyMMddHHmmss", "yyyyMMddHHmmss");
        } else if (value.contains("yyyyMMdd")) {
            value = fetchBatchNumber(value, "yyyyMMdd", "yyyyMMdd");
        } else if (value.contains("YYYY")) {
            value = fetchBatchNumber(value, "yyyy", "YYYY");
        } else if (value.contains("YY")) {
            value = fetchBatchNumber(value, "yy", "YY");
        } else if (value.contains("fetchBatchNumber(")) {
            value = fetchBatchNumber(value);
        }
        return value;
    }

    /**
     * 获取批次号
     * @param key
     * @return
     */
    private String fetchBatchNumber(String key) {
        String result = "";
        Matcher m = Pattern.compile("(?<=fetchBatchNumber\\().*?(?=\\))").matcher(key);
        if(m.find()) {
            result = getNextVal(m.group());
        }
        result = key.replaceAll("fetchBatchNumber\\(([^)]+)\\)", result);
        return result;
    }


    /**
     * 获取批次号
     * @param value
     * @param formatStr
     * @param containValue
     * @return
     */
    private String fetchBatchNumber(String value, String formatStr, String containValue) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(formatStr);
        String formatTime = LocalDateTime.now().format(dtf);
        String newValue = value.replace(containValue, formatTime);
        newValue = getNextVal(newValue);
        return newValue;
    }

    @Transactional
    @Override
    public String getNextVal(String name) {
        Map<String, String> param = new HashMap();
        param.put("name", name);
        return getNextVal(param);
    }

    /**
     * 获取下一个批号值
     *
     * @param param 参数
     * @return 返回值
     */
    @Transactional
    @Override
    public String getNextVal(Map<String, String> param) {
        String name = param.get("name");
        QueryWrapper<BatchNumber> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        List<BatchNumber> batchNumbers = batchNumberService.list(queryWrapper);
        String batchNo;
        try {
            if(batchNumbers!=null && batchNumbers.size()>0){
                BatchNumber batchNumber = batchNumbers.get(0);
                Integer currentValue = batchNumber.getCurrentValue();
                Integer increment = batchNumber.getIncrement();
                Integer nextVal = currentValue + increment;
                batchNumber.setCurrentValue(nextVal);
                batchNumberService.update(batchNumber,queryWrapper);
                batchNo = name + "-" + nextVal;
            }else{
                BatchNumber batchNumber = new BatchNumber();
                batchNumber.setName(name);
                batchNumber.setCurrentValue(1);
                batchNumber.setIncrement(1);
                batchNumberService.save(batchNumber);
                batchNo = name + "-" + 1;
            }
            return batchNo;
        }catch (Exception ex){
            throw new BusinessException("999999","获取下一个批次号数据异常", ex);
        }
    }

    /**
     * 获取下一个批号值
     *
     * @param code 参数
     * @return 返回值
     */
    @Transactional
    @Override
    public String getNextValByCode(String code) {
        try {
            QueryWrapper<BatchNumber> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", code);
            BatchNumber batchNumber = batchNumberService.getOne(queryWrapper);
            Integer currentValue = batchNumber.getCurrentValue();
            Integer increment = batchNumber.getIncrement();
            Integer nextVal = currentValue + increment;
            batchNumber.setCurrentValue(nextVal);
            batchNumberService.update(batchNumber,queryWrapper);
            return batchNumber.getName() + "-" + nextVal;
        }catch (Exception ex){
            throw new BusinessException("999999","获取下一个批次号数据异常", ex);
        }
    }
}




